// 定义所有可选项
const platforms = [
    {
        name: 'Zread',
        domain: 'zread.ai'
    },
    {
        name: 'DeepWiki',
        domain: 'deepwiki.com'
    },
    {
        name: 'ReadmeX',
        domain: 'readmex.com'
    }
];

// 检查当前页面是否为GitHub项目页面
function isGitHubProjectPage(url) {
    if (!url || !url.includes('github.com')) {
        return false;
    }

    const urlObj = new URL(url);
    const path = urlObj.pathname;

    // 匹配格式: /username/repository 或 /username/repository/...
    const projectPattern = /^\/[^\/]+\/[^\/]+(?:\/.*)?$/;
    const excludePatterns = [
        /^\/$/,                          // 首页
        /^\/search/,                     // 搜索页
        /^\/topics/,                     // 话题页
        /^\/trending/,                   // 趋势页
        /^\/explore/,                    // 探索页
        /^\/notifications/,              // 通知页
        /^\/settings/,                   // 设置页
        /^\/[^\/]+$/,                    // 用户主页
        /^\/orgs\//,                     // 组织页
        /^\/sponsors/,                   // 赞助页
    ];

    if (!projectPattern.test(path)) {
        return false;
    }

    for (const pattern of excludePatterns) {
        if (pattern.test(path)) {
            return false;
        }
    }

    return true;
}

// 创建菜单项
function createMenuItem(platform, currentUrl) {
    const menuItem = document.createElement('div');
    menuItem.className = 'menu-item';

    menuItem.innerHTML = `
        <div>
            <div class="platform-name">Analyze with ${platform.name}</div>
        </div>
    `;

    menuItem.addEventListener('click', () => {
        const targetUrl = currentUrl.replace('github.com', platform.domain);
        chrome.tabs.create({ url: targetUrl });
        window.close();
    });

    return menuItem;
}

// 初始化popup
document.addEventListener('DOMContentLoaded', () => {
    // 获取当前活动标签页
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        const currentTab = tabs[0];
        const currentUrl = currentTab.url;

        const menuContainer = document.getElementById('menu-container');
        const errorMsg = document.getElementById('error-msg');

        if (isGitHubProjectPage(currentUrl)) {
            // 是GitHub项目页面，显示菜单选项
            platforms.forEach(platform => {
                const menuItem = createMenuItem(platform, currentUrl);
                menuContainer.appendChild(menuItem);
            });
        } else {
            // 不是GitHub项目页面，显示错误信息
            errorMsg.style.display = 'block';
        }
    });
});